package com.ken.mqspring.converter;

import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;


/**
 * 图片类自定义处理类
 * Created by renchongyu on 2018/11/22.
 */
public class ImageMessageConverter implements MessageConverter {


    @Override
    public org.springframework.amqp.core.Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        throw new MessageConversionException("Image exception error");
    }

    @Override
    public Object fromMessage(org.springframework.amqp.core.Message message) throws MessageConversionException {
        System.out.println("Image MessageConverter start");
        String extName = (String)message.getMessageProperties().getHeaders().get("extName");
        if(extName==null){
            extName = "png";
        }

        byte[] body = message.getBody();
        String fileName = UUID.randomUUID().toString();
        //此处path适合mac和linux。windows可以用盘符代替例：d://002
        String path = "/Users/renchongyu/image/"+fileName+"."+extName;
        File file = new File(path);
        try {
            Files.copy(new ByteArrayInputStream(body), file.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Image MessageConverter end");
        return file;
    }

}
